from flask import jsonify
from app.libs.redprint import Redprint
from app.libs.tools import giftorder
from app.models.taobao_orders import taobao_orders
from app.models.base import db
from app.validators.order import OrderForm, BanOrderForm

api = Redprint('order')


@api.route('/free', methods=['POST'])
def free():
    form = OrderForm().validate_for_api()
    free = giftorder(form.order_number.data)
    tb_info = taobao_orders.query.filter_by(order_number=form.order_number.data).first()
    if not tb_info or tb_info.total == 0:
        return jsonify([])
    if tb_info.has_exchange == 0:
        with db.auto_commit():
            tb_model = taobao_orders()
            tb_model.order_number = free
            tb_model.total = 0
            tb_model.amount = 0
            tb_model.remain = tb_info.total
            tb_model.shop = tb_info.shop
            tb_model.order_detail = free
            taobao_orders.query.filter_by(order_number=form.order_number.data).update({'has_exchange': 1})
            db.session.add(tb_model)
    return jsonify([{'order_number': free, 'total': tb_info.total}])